<template>
  <div>
    <Header :title="'返回'" :hasBackPath="true" @headerBack="headerBack"></Header>
    <a-card>
      <a-spin :spinning="spinning" size="large">
        <div class="form-contanier">
          <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol" style="width: 100%">
            <a-form-model-item label="小程序" prop="appId" v-if="id == 'add'">
              <a-select v-model="form.appId" style="width: 80%">
                <a-select-option :value="item.appId" v-for="item in env === 'production' ? brandListPro : brandList" :key="item.weid">{{ item.brandName }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="小程序" prop="appId" v-else>{{ form.appName }}</a-form-model-item>
            <a-form-model-item label="位置" prop="position" v-if="id == 'add'">
              <a-select v-model="form.position" style="width: 80%">
                <a-select-option :value="item.code" :key="index" v-for="(item, index) in positionList">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-model-item>
            <a-form-model-item label="位置" prop="appId" v-else>{{ form.posManagerName }}</a-form-model-item>
            <a-form-model-item label="图片" prop="imgList">
              <JImageUpload :uploadParams="getUploadParams()" :isMultiple="false" :fileSize="1" :accept="'image/*'" @fileChange="fileImageChange" v-model="imgList"></JImageUpload>
              <div class="upload__tip" style="line-height: 16px">{{ imgTips[form.position] }}</div>
            </a-form-model-item>
            <div v-show="form.position">
              <a-form-model-item label="排序" prop="sortNo" v-if="form.position != 1">
                <a-input-number :min="1" :max="99" v-model="form.sortNo" @change="v => handleChange(v, 'sortNo')" />
                <span class="upload__tip" style="line-height: 16px; margin-left: 16px">1-99，数字越大的越往前排</span>
              </a-form-model-item>
              <a-form-model-item label="标题" v-if="form.position == 2" prop="titleTxt"> <a-input v-model="form.titleTxt" :maxLength="4" style="width: 80%" /></a-form-model-item>
              <a-form-model-item label="备注"> <a-textarea v-model="form.remark" :auto-size="{ minRows: 3, maxRows: 6 }" style="width: 80%" /></a-form-model-item>
              <template v-if="form.position != 1">
                <a-form-model-item label="适用人群包">
                  <a-button icon="plus" type="link" @click="handlePeople">添加</a-button><span>(只允许选择一个)</span>
                  <a-table :dataSource="targetPerson" :columns="targetColums" :pagination="false" :rowKey="(r, index) => index">
                    <span slot="action" slot-scope="text, record, index">
                      <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(index, 'person')">
                        <a><a-icon type="delete" /></a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                </a-form-model-item>
                <a-form-model-item label="适用门店">
                  <a-button type="link" icon="plus" @click="handleShop">添加</a-button><span>(只允许选择一个)</span>
                  <a-table :dataSource="shopList" :columns="shopColums" :pagination="false" :rowKey="(r, index) => index">
                    <span slot="action" slot-scope="text, record, index">
                      <a-popconfirm title="确定删除吗?" ok-text="Yes" cancel-text="No" @confirm="handleDelete(index, 'shop')">
                        <a><a-icon type="delete" /></a>
                      </a-popconfirm>
                    </span>
                  </a-table>
                </a-form-model-item>
                <p style="color: #f5222d; padding-left: 72px">注：人群包条件和门店包条件取交集。不填表示所有人群。</p>
                <a-form-model-item label="跳转类型" prop="jumpType">
                  <a-select v-model="form.jumpType" style="width: 80%">
                    <a-select-option :value="1">小程序</a-select-option>
                    <a-select-option :value="2">视频号</a-select-option>
                    <a-select-option :value="3">H5链接</a-select-option>
                  </a-select>
                </a-form-model-item>

                <a-form-model-item label="app id" prop="miniAppId" v-if="form.jumpType == 1">
                  <a-input v-model="form.miniAppId" style="width: 80%" />
                </a-form-model-item>
                <a-form-model-item label="小程序路径" prop="miniAppPath" v-if="form.jumpType == 1">
                  <a-input v-model="form.miniAppPath" style="width: 80%" />
                </a-form-model-item>
                <a-form-model-item label="视频号 id" prop="videoId" v-if="form.jumpType == 2">
                  <a-input v-model="form.videoId" style="width: 80%" />
                </a-form-model-item>
                <a-form-model-item label="H5链接" prop="h5Link" v-if="form.jumpType == 3">
                  <a-input v-model="form.h5Link" style="width: 80%" />
                </a-form-model-item>
              </template>
            </div>
            <a-form-model-item label="显示时间" prop="showTimeType">
              <a-select v-model="form.showTimeType" show-search style="width: 80%">
                <a-select-option :value="0">自定义</a-select-option>
                <a-select-option :value="1">按用户生日</a-select-option>
              </a-select>
            </a-form-model-item>
            <template v-if="form.showTimeType == 0">
              <a-form-model-item prop="timePicker" :labelCol="labelCol" :wrapperCol="{ span: 18, offset: 5 }">
                <a-range-picker
                  :show-time="{
                    hideDisabledOptions: true,
                    defaultValue: [moment('00:00:00', 'HH:mm:ss'), moment('23:59:59', 'HH:mm:ss')]
                  }"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="form.timePicker"
                  style="width: 80%"
                  valueFormat="YYYY-MM-DD HH:mm:ss"
                  format="YYYY-MM-DD HH:mm:ss"
                />
              </a-form-model-item>
            </template>
            <template v-if="form.showTimeType == 1">
              <a-form-model-item prop="birthdayTime" :wrapperCol="{ span: 18, offset: 5 }">
                <a-radio-group name="radioGroup" v-model="form.birthdayTime" @change="onChange">
                  <a-radio :value="0">生日前一个月至生日月结束</a-radio>
                  <a-radio :value="1">仅生日当月</a-radio>
                </a-radio-group>
              </a-form-model-item>
            </template>

            <a-form-model-item :wrapper-col="{ span: 24 }">
              <div style="text-align: center">
                <a-button type="primary" :loading="saveLoading" @click="onSubmit" v-if="!(id != 'add' && form.status == 2)">发布</a-button>
                <template v-if="id != 'add' && form.status != 2">
                  <a-button style="margin-left: 10px" @click="onSubmit('goLive')" v-if="form.status == 0">启用</a-button>
                  <a-button style="margin-left: 10px" @click="onSubmit('forbidden')" v-if="form.status == 1">禁用</a-button>
                </template>
                <a-button style="margin-left: 10px" @click="headerBack">取消</a-button>
              </div>
            </a-form-model-item>
          </a-form-model>
        </div>
      </a-spin>
    </a-card>
    <PeoplePagModal ref="peoplePagModal" :logVisible.sync="logVisible" :channel="'member'" @updatePeople="updatePeople"> </PeoplePagModal>
    <ShopPagModal ref="shopPagModal" :logVisible.sync="logVisibleShop" @updateStore="updateStore"></ShopPagModal>
  </div>
</template>
<script>
import moment from 'moment'
import 'moment/locale/zh-cn'
import globalData from '@/assets/js/common'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
import PeoplePagModal from '@/views/marketingCenter/components/peoplePagModal'
import ShopPagModal from '@/views/marketingCenter/components/shopPagModal'
import Header from '@/views/box/components/layouts/Header'
import { mixin } from './mixin'
import { posTemplateCreate, posTemplateUpdate, posTemplateInfo, posManagerList } from '@/api/marketingCenter/memberTask'
let targetColums = [
  { title: '人群包ID', dataIndex: 'id' },
  { title: '人群包名称', dataIndex: 'name' },
  { title: '操作', scopedSlots: { customRender: 'action' } }
]
let shopColums = [
  { title: '门店包ID', dataIndex: 'id' },
  { title: '门店包名称', dataIndex: 'name' },
  { title: '操作', scopedSlots: { customRender: 'action' } }
]
export default {
  mixins: [mixin],
  components: {
    JImageUpload,
    Header,
    PeoplePagModal,
    ShopPagModal
  },
  data() {
    return {
      spinning: false,
      labelCol: { span: 5 },
      wrapperCol: { span: 18 },
      id: '',
      rules: {
        appId: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
        position: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
        sortNo: [{ required: true, message: '请输入排序', trigger: ['blur', 'change'] }],
        titleTxt: [{ required: true, message: '请输入九宫格标题', max: 4, trigger: 'blur' }],
        imgList: [{ required: true, trigger: ['blur', 'change'], validator: this.validatorImg, type: 'array' }],
        jumpType: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
        miniAppId: [{ required: true, message: '请输入', trigger: 'blur' }],
        miniAppPath: [{ required: true, message: '请输入', trigger: 'blur' }],
        h5Link: [{ required: true, message: '请输入', trigger: 'blur' }],
        videoId: [{ required: true, message: '请输入', trigger: 'blur' }],
        showTimeType: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
        timePicker: [{ required: true, message: '请选择时间', trigger: ['blur', 'change'] }],
        birthdayTime: [{ required: true, message: '请选择', trigger: ['blur', 'change'] }]
      },
      form: {
        appId: null,
        position: null,
        imgList: [],
        sortNo: 1,
        titleTxt: '',
        remark: '',
        timePicker: undefined,
        jumpType: null,
        showTimeType: null,
        birthdayTime: null
      },
      imgList: [],
      targetPerson: [],
      targetColums,
      shopList: [],
      shopColums,
      logVisible: false,
      logVisibleShop: false,
      saveLoading: false,
      channelList: [],
      env: process.env.NODE_ENV
    }
  },
  mounted() {
    this.initialPage()
  },
  methods: {
    moment,
    async initialPage() {
      this.id = this.$route.params.id
      let type = this.$route.params.type

      if (this.id != 'add') {
        await this.fetchData()
        if (type == 'copy') {
          this.id = 'add'
        }
      }
    },
    fetchData() {
      this.spinning = true
      return posTemplateInfo(this.id).then(res => {
        if (res.code == 0) {
          const { data } = res
          this.form = data
          this.imgList = [data.image]

          this.targetPerson = data.adaptPeopleId || data.adaptPeopleName ? [{ id: data.adaptPeopleId, name: data.adaptPeopleName }] : []
          this.shopList = data.adaptStoreId || data.adaptStoreName ? [{ id: data.adaptStoreId, name: data.adaptStoreName }] : []

          this.$nextTick(() => {
            if (this.form.showTimeType == 0) {
              this.$set(this.form, 'timePicker', [data.startTime, data.endTime])
            }
          })
        } else {
          this.$message.warning(res.msg)
        }
        this.spinning = false
      })
    },
    headerBack() {
      this.$router.back()
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileImageChange(list) {
      this.form.imgList = list.length > 0 ? list : []
    },
    validatorImg(rule, value, callback) {
      if (this.form.imgList.length) {
        callback()
      } else {
        callback('请上传图片')
      }
    },
    handleChange(v, name) {
      this.form[name] = v
    },
    onChange(e) {
      this.form.birthdayTime = e.target.value
    },
    handleDelete(index, type) {
      if (type == 'person') {
        this.targetPerson.splice(index, 1)
      }
      if (type == 'shop') {
        this.shopList.splice(index, 1)
      }
    },
    handlePeople() {
      this.$refs.peoplePagModal.getLog('parent')
      this.logVisible = true
    },
    updatePeople(record) {
      let newRecord = {
        id: record.groupId,
        name: record.groupName,
        states: record.states
      }
      this.targetPerson = [newRecord]
      this.$message.success('添加成功')
    },
    handleShop() {
      this.$refs.shopPagModal.getLog('parent')
      this.logVisibleShop = true
    },
    updateStore(record) {
      let newRecord = {
        id: record.storePackageId,
        name: record.storePackageName
      }
      this.shopList = [newRecord]
      this.$message.success('添加成功')
    },
    fetchPosManageList() {
      let params = {
        requestData: {
          appId: this.form.appId
        }
      }
      return posManagerList(params).then(res => {
        if (res.code == 0) {
          this.channelList = res.data
        }
      })
    },
    onSubmit(operate) {
      this.$refs.ruleForm.validate(async valid => {
        this.spinning = true
        this.saveLoading = true
        if (valid) {
          await this.fetchPosManageList()
          let formValue = JSON.parse(JSON.stringify(this.form))

          formValue.image = this.form.imgList[0].url
          delete formValue.imgList
          delete formValue.enableStatus
          delete formValue.status
          delete formValue.id

          if (this.form.position != 1) {
            if (this.targetPerson.length) {
              formValue.adaptPeopleId = this.targetPerson[0].id
              formValue.adaptPeopleName = this.targetPerson[0].name
            } else {
              formValue.adaptPeopleId = null
              formValue.adaptPeopleName = null
            }
            if (this.shopList.length) {
              formValue.adaptStoreId = this.shopList[0].id
              formValue.adaptStoreName = this.shopList[0].name
            } else {
              formValue.adaptStoreId = null
              formValue.adaptStoreName = null
            }
          } else {
            delete formValue.adaptPeopleId
            delete formValue.adaptPeopleName
            delete formValue.adaptStoreId
            delete formValue.adaptStoreName
            delete formValue.jumpType
          }

          if (formValue.showTimeType == 0) {
            formValue.startTime = this.form.timePicker[0]
            formValue.endTime = this.form.timePicker[1]
            delete formValue.timePicker
          } else {
            delete formValue.timePicker
            delete formValue.startTime
            delete formValue.endTime
          }

          console.log(formValue)

          if (this.id == 'add') {
            if (process.env.NODE_ENV === 'production') {
              formValue.appName = this.brandListPro.filter(e => e.appId == this.form.appId)[0].brandName
            } else {
              formValue.appName = this.brandList.filter(e => e.appId == this.form.appId)[0].brandName
            }

            formValue.posManagerId = this.channelList.filter(e => e.position == this.form.position)[0].id
            formValue.posManagerName = this.positionList.filter(e => e.code == this.form.position)[0].name

            this.addChannel(formValue)
          } else {
            formValue.id = this.id
            if (operate == 'goLive') {
              this.saveLoading = false
              this.handleGoLive(formValue)
            } else if (operate == 'forbidden') {
              this.saveLoading = false
              this.handleForbidden(formValue)
            } else {
              this.editChannel(formValue)
            }
          }
        } else {
          this.spinning = false
          this.saveLoading = false
        }
      })
    },
    // 新增
    addChannel(formValue) {
      let params = {
        requestData: formValue
      }
      posTemplateCreate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('新建成功')
          this.headerBack()
        } else {
          this.$message.warning(res.msg)
        }
        this.spinning = false
        this.saveLoading = false
      })
    },
    // 编辑
    editChannel(formValue) {
      let params = {
        requestData: formValue
      }
      posTemplateUpdate(params).then(res => {
        if (res.code == 0) {
          this.$message.success('修改成功')
          this.headerBack()
        } else {
          this.$message.warning(res.msg)
        }
        this.spinning = false
        this.saveLoading = false
      })
    },
    // 启用
    handleGoLive(data) {
      let self = this
      this.$confirm({
        title: '确认要启用吗？',
        okText: '确认启用',
        onOk() {
          data.enableStatus = 0
          self.editChannel(data)
        },
        onCancel() {
          self.spinning = false
        }
      })
    },
    // 禁用
    handleForbidden(data) {
      let self = this
      this.$confirm({
        title: '确认要禁用吗？',
        okText: '确认禁用',
        onOk() {
          data.enableStatus = 1
          self.editChannel(data)
        },
        onCancel() {
          self.spinning = false
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.form-contanier {
  max-width: 800px;
  width: 80%;
  margin: 0 auto;
  position: relative;
}
.wrapper {
  position: absolute;
  width: 100%;
  height: calc(100% - 52px);
  background: rgba(0, 0, 0, 0);
  top: 0;
  left: 0;
}
</style>

